<?php 
namespace app\wework\controller\job;

use app\BaseController;
use think\facade\Db;
use app\wework\model\Helper;
use app\wework\model\BaseModel;
use app\wework\model\user\send\GroupSendModel;
use app\wework\model\QyWechatApi;
use think\facade\Log;
use think\queue\Job;
use app\wework\controller\Base;


/**
* 定时任务，实时发送提醒
*/
class Colonization extends Base{
	public function index(){
		$config_list = Db::table('kt_wework_config')->where(["customer_status"=>1])->column("wid");
		if(!$config_list) return success("操作失败");
		foreach ($config_list as $user) {
			$this->coloniz($user);
		}

		return success("操作成功");
	}

	public function coloniz($wid){
		$list = Db::table("kt_wework_tag_group")->where(["wid"=>$wid,"status"=>0])->json(["msg_id"])->select()->toArray();
		if(!$list)return success("操作完成");
		foreach($list as $value){
			foreach($value["msg_id"] as $msg_id){
				$res = QyWechatApi::getGroupmsgTask($wid,$msg_id);
				if(!$res["task_list"])continue;
				foreach ($res["task_list"] as $task_list){
					$user = Helper::getUser(["wid"=>$wid,"userid"=>$task_list["userid"]]);
					$is_set = Db::table("kt_wework_tag_group_user")->where(["pid"=>$value["id"],"staff_id"=>$user["id"],"msg_id"=>$msg_id])->find();
					$data["wid"] = $wid;
					$data["pid"] = $value["id"];
					$data["staff_id"] = $user["id"];
					$data["msg_id"] = $msg_id;
					$data["status"] = $task_list["status"];
					if($is_set)Db::table("kt_wework_tag_group_user")->where(["pid"=>$value["id"],"staff_id"=>$user["id"],"msg_id"=>$msg_id])->save($data);
					if(!$is_set)Db::table("kt_wework_tag_group_user")->insertGetId($data);
				}
			}
			$size = Db::table("kt_wework_tag_group_user")->where(["pid"=>$value["pid"],"status"=>0])->count();
			if(!$size)Db::table("kt_wework_tag_group")->where(["id"=>$value["id"]])->update(["status"=>1]);
		}
		return success("操作成功");
	}
}